package com.example.figurehecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.domain.dto.HumanityDTO;
import com.example.figurehecheng.domain.entity.Humanity;
import com.example.figurehecheng.domain.entity.Image;
import com.example.figurehecheng.domain.entity.News;
import com.example.figurehecheng.domain.vo.HumanityVO;
import com.example.figurehecheng.mapper.HumanityMapper;
import com.example.figurehecheng.service.IHumanityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.figurehecheng.service.IImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 人文关系表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-18
 */
@Service
@Slf4j
public class HumanityServiceImpl extends ServiceImpl<HumanityMapper, Humanity> implements IHumanityService {
    @Autowired
    private IImageService imageService;
    @Autowired
    private IHumanityService humanitService;

    /**
     * 创建人文
     *
     * @param dto
     * @return
     */
    @Override
    public long createHumanity(HumanityDTO dto) {
        Humanity humanity = new Humanity();
        if (dto == null) {
            throw new IllegalArgumentException("NewsDTO 不能为 null");
        }
        // 2. 处理图片ID数组
        String imgidlist = "";
        if (dto.getImageIds() != null && !dto.getImageIds().isEmpty()) {
            imgidlist = dto.getImageIds().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(","));
        }
        try {
            BeanUtils.copyProperties(dto, humanity);
            humanity.setMid(BaseContext.getCurrentId().intValue());
            humanity.setCreateTime(LocalDateTime.now());
            humanity.setUpdateTime(LocalDateTime.now());
            humanity.setImageId(imgidlist);
            save(humanity);
            return humanity.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return humanity.getId();
    }


    /**
     * 获取人文信息
     *
     * @return
     */
    @Override
    public HumanityVO getHumanityDetail(Long id) {
        Humanity humanity = getById(id);
        System.out.println("jhsaj"+id);
        if (humanity == null) {
            throw new RuntimeException("人文存在");
        }
        //转化为VO
        HumanityVO vo = new HumanityVO();
        BeanUtils.copyProperties(humanity, vo);
        String imageId = humanitService.lambdaQuery().eq(Humanity::getId, humanity.getId()).one().getImageId();
        String[] imageIds = imageId.split(",");
        Long[] numbers = new Long[imageIds.length];
        for (int i = 0; i < imageIds.length; i++) {
            numbers[i] = Long.parseLong(imageIds[i]);
        }
        List<String> imageList = new ArrayList<>();
        for (Long number : numbers) {
            Image image = imageService.lambdaQuery().eq(Image::getId, number).one();
            if (image != null) {
                imageList.add(image.getUrl());
            }
        }
        if (!imageList.isEmpty()) {
            vo.setImages(imageList);
        }
        return vo;
    }

    /**
     * 修改人文
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHumanity(HumanityDTO dto) {
        // 1. 参数校验
        if (dto == null || dto.getId() == null) {
            log.warn("更新人文信息失败: 参数不合法, dto={}", dto);
            return false;
        }
        // 2. 查询现有数据（避免全量覆盖问题）
        Humanity existing = getById(dto.getId());
        if (existing == null) {
            log.warn("更新人文信息失败: 记录不存在, id={}", dto.getId());
            return false;
        }
        // 3. 使用安全属性拷贝
        try {
            BeanUtils.copyProperties(dto, existing); // 只更新非空字段
        } catch (RuntimeException e) {
            log.error("更新人文信息失败: 属性拷贝失败, dto={}", dto, e);
            return false;
        }
        // 4. 设置更新时间和更新人（根据业务需求）
        existing.setUpdateTime(LocalDateTime.now());
        // 5. 更新并返回结果
        return updateById(existing);
    }

    /**
     * 获取人文列表
     *
     * @return
     */
    @Override
    public List<HumanityVO> getHumanityList() {
        // 1. 预加载所有图片数据（解决N+1问题）
        List<Humanity> humanityList = this.list(new LambdaQueryWrapper<Humanity>()
                .orderByDesc(Humanity::getCreateTime));
        // 收集所有图片ID（处理空值和无效ID）
        List<Long> allImageIds = humanityList.stream()
                .map(Humanity::getImageId)
                .filter(StringUtils::isNotBlank)
                .flatMap(imageId -> Arrays.stream(imageId.split(",")))
                .map(String::trim)
                .filter(id -> !id.isEmpty())
                .map(id -> {
                    try {
                        return Long.parseLong(id);
                    } catch (NumberFormatException e) {
                        return null; // 过滤无效ID
                    }
                })
                .filter(Objects::nonNull)
                .collect(toList());
        // 批量查询图片数据（使用Map提升查找效率）
        Map<Long, String> imageUrlMap = imageService.listByIds(allImageIds)
                .stream()
                .collect(Collectors.toMap(
                        Image::getId,
                        Image::getUrl,
                        (existing, replacement) -> existing));
        // 2. 转换处理
        return humanityList.stream()
                .map(humanity -> {
                    HumanityVO vo = new HumanityVO();
                    BeanUtils.copyProperties(humanity, vo);
                    vo.setCreateTime(humanity.getCreateTime());
                    // 3. 处理图片逻辑
                    List<String> imageUrls = Arrays.stream(humanity.getImageId().split(","))
                            .map(String::trim)
                            .filter(id -> !id.isEmpty())
                            .map(id -> {
                                try {
                                    return Long.parseLong(id);
                                } catch (NumberFormatException e) {
                                    return null;
                                }
                            })
                            .filter(Objects::nonNull)
                            .map(imageUrlMap::get)
                            .filter(Objects::nonNull)
                            .collect(toList());
                    if (!imageUrls.isEmpty()) {
                        vo.setCoverImage(imageUrls.get(0));
                        vo.setImages(imageUrls); // 按需开启
                    }
                    return vo;
                })
                .collect(toList());
    }
}
